<template>
	<view class="app-white-list-page">
		<Tips title="小贴士" :des="des" />
		<view class="white-list" v-if="list.length">
			<list ref="listRef" loadmoreoffset="100" @loadmore="loadmore">
			    <view v-for="(item, i) in list" :key="i" class="app-item">
						<image style="width: 50px;height: 50px;" :src="item.appImage" />
						<view class="app-name">{{ item.appName}}</view>
						<view class="right-handler">
							<view class="time-move">
								<view class="set-every-day-time">
									<view class="custom-picker-style">
										<CustomPicker v-if="show" :index="queryUseTime(item.useTimeInt)" :i="i" :data="times" @onSelect="({index, i}) =>onSelect({index, i, app:item})" />
									</view>
								</view>
								<view class="set-every-day-time remove" @click="() => remove(item)">移除</view>
							</view>
						</view>
			    </view>
			  </list>
		</view>
		<view v-else>
			 <Empt description="暂无应用白名单" />
		</view>
		
		<view class="add-white-app-post-bottom" @click="jumpPage">
			<!-- <van-icon name="add" color="#2BC888" /> -->
			<icon type="plusempty" size="26" />
			<view class="txt">添加白名单应用</view>
		</view>
							
	</view>
</template>

<script lang="ts" setup>
	import {ref,computed, onMounted} from 'vue'
	import Tips from "@/components/tips/index.vue"
	import CustomPicker from './customPicker.vue';
	import Empt from "@/components/Empt/index.vue"
	import { homeServer } from '@/common/index'
	import { useStudentListStore } from "@/stores/useStudentList.js"
	import { urlHelp, mock } from '@/utils/index'
	import {secondsToMinutesOrHours, minutesToSeconds, hoursToSeconds, minutesToHoursMinutes} from "./help.js"
	import {onShow} from "@dcloudio/uni-app"
	import { useBound } from "@/hooks/useBound.ts"
	const {tipBoundStudent, studentIsEmpt} = useBound();
		
	const studentStore = useStudentListStore();
	const curStd = computed(() => studentStore.currentStudent);
	
	const page = ref(1);
	const size = ref(1000);
	const list = ref([]);
	
	const des = ref([
		'1.添加到白名单的应用, 可以只有使用不受管控',
		{
			text: '2.使用帮助',
			type: 'whiteList'
		}
	]);
	
	
	function insertItem(arr, newItem) {  
	    // 遍历数组，检查是否已经存在具有相同value的对象  
	    let exists = arr.some(item => item.value === newItem.value);  
	  
	    // 如果不存在，则找到第一个value大于或等于newItem.value的元素索引  
	    if (!exists) {  
	        let insertIndex = arr.findIndex(item => item.value >= newItem.value);  
	  
	        // 如果没有找到（即所有现有元素的value都小于newItem.value），则插入到数组末尾  
	        if (insertIndex === -1) {  
	            arr.push(newItem);  
	        } else {  
	            // 否则，插入到找到的元素之前  
	            arr.splice(insertIndex, 0, newItem);  
	        }  
	    }  
	    // 如果存在，则不执行任何操作  
	}
	
	// 设置mock
	const setMock = () => {
		const data = JSON.parse(JSON.stringify(mock.WHITE_APP.data));
		list.value = data?.map(item => urlHelp.imgAddPrefix(item,  'appImage'))
	}
	
	// 获取白名单
	const parentWhitelist = async () => {
		const studentId = curStd.value?.id;
		if(!studentId){
			console.log('没有学生di')
			return
		}
		try{
			const { status, data} = await homeServer.parentWhitelist({
				page: page.value, 
				size: size.value,
				studentId
			});
			if(status === '200'){
				console.log('获取白名单', data)
				if(page.value === 1){
					list.value = []
				}
				list.value = data?.map(item => urlHelp.imgAddPrefix(item,  'appImage'))
			}
		}catch(e){
			console.log(e)
			//TODO handle the exception
		}
	}
	
	// 设置可用时长
	const updateUseTimeInt = async (app, useTimeInt, useTimeStr) => {
	const studentId = curStd.value?.id;
	if(!studentId){
		console.log('没有学生di')
		return
	}
		try{
			const {status} = await homeServer.updateUseTimeInt({
				id: app.id,
				appName: app.appName,
				packageName: app.packageName,
				studentId:studentId,
				useTimeInt,
				useTimeStr
			});
			if(status === '200'){
				uni.showToast({
					title:"设置成功",
					success() {
						parentWhitelist()
					}
				})
			}
		}catch(e){
			console.log(e)
			//TODO handle the exception
		}
	}
	onMounted(() => {
		if(!mock.isLogged()){
			setMock()
		} else {
			parentWhitelist()
		}
		
		
	})
	onShow(() => {
		if(!mock.isLogged()){
			setMock()
		} else {
			parentWhitelist()
		}
	})
	
	
	const listRef = ref()
	const show = ref(true);
	 // 重置 loadmore
	const resetLoadMore = () =>{
        listRef?.vue?.resetLoadmore();
    }
	const loadmore = () => {
		console.log('下拉触底加载更多')
	}
	
	const data = [
		{
			index:0
		},
		{
			index:0
		},
		{
			index:2
		},
		{
			index:3
		},
		{
			index:4
		}
	];
	const normal = ref(true);
	const opacityStyle = computed(() => {
		return {
			opacity: normal.value ? 0 : 1
		}
	})
	const onSelect = async  ({index,i, app}) => {
		console.log("onSelect", index, i, app);
		if(!mock.isLogged()){
			tipBoundStudent();
			return
		}
		show.value = false;
		// data[i]["index"] = index;
		normal.value = false;
		show.value = true;
	    updateUseTimeInt(app, timeData.value[index]['value'], timeData.value[index]['name'])
	}
	
	// const times = [
	// 	'不设置',
	// 	'5分钟',
	// 	'10分钟',
	// 	'30分钟',
	// 	'1小时',
	// 	'2小时',
	// 	'3小时'
	// ]
	const timeData =  ref([
		{
			name: '不设置',
			value: 0
		},
		{
			name: '5分钟',
			value: 5
		},
		{
			name: '15分钟',
			value: 15
		},
		{
			name: '30分钟',
			value: 30
		},
		{
			name: '45分钟',
			value: 45
		},
		{
			name: '1小时',
			value:60
		},
		{
			name: '1小时15分',
			value:75
		},
		{
			name: '1小时30分',
			value:90
		},
		{
			name: '2小时',
			value:120
		},
		{
			name: '2小时30分',
			value:150
		},
		{
			name: '3小时',
			value:180
		},
		{
			name: '4小时',
			value:240
		},
		{
			name: '5小时',
			value:300
		},
	]);
	const times = computed(() => timeData.value.map(item => item.name));
	
	const queryUseTime = (useTimeInt: number) => {
		if(typeof useTimeInt !== 'number'){
			return 0 
		}
		return timeData.value.findIndex(item => item.value === Number(useTimeInt))
	}
	// 移除白名单
	const appWhitelistDelete = async (app) => {
		const studentId = curStd.value?.id;
		if(!studentId){
			console.log('没有学生di')
			return
		}
		try{
			const {status, data} = await homeServer.appWhitelistDelete({
				studentId,
				appName: app.appName,
				id: app.id,
				packageName: app.packageName
			});
			if(status === '200'){
				uni.showToast({
					title:"移除成功",
					icon:"success",
					success() {
						parentWhitelist()
					}
				})
			}
		}catch(e){
			console.log(e)
			//TODO handle the exception
		}
	}

	const remove = (app) => {
		if(!mock.isLogged()){
			tipBoundStudent();
			return
		}
		uni.showModal({
			content:"确认移除吗？",
			cancelText:"取消",
			confirmText:"确定",
			success({confirm}) {
				if(confirm){
					appWhitelistDelete(app)
				}
			}
		})
	}
	
	
	const jumpPage = () => {
		if(!mock.isLogged()){
			tipBoundStudent();
			return
		}
		uni.navigateTo({
			url:'/pagesB/addAppWhiteSearch/index'
		})
	}
</script>

<style>
	page{
		background-color: #f7fbfe;
	}
</style>
<style lang="scss" scoped>
	.app-white-list-page{
		.white-list{
			background-color: #fff;
			margin-top: 40upx;
			padding: 40upx 20upx 180upx 20upx;
			.app-item{
				display: flex;
				align-items: center;
				margin-bottom: 30upx;
				// justify-content: flex-start;
				// align-items: center;
				// margin-bottom: 20upx;
				position: relative;
				.app-name{
					margin-left: $appIconLeftMarg;
					font-size: $appIconTxt;
					display: flex;
					align-items: center;
					margin-bottom: 0;
				}
				.right-handler{
					position: absolute;
					right: 0;
					// top: 35%;
					display: flex;
					justify-content: flex-end;
					.time-move{
						display: flex;
						align-items: center;
						.set-every-day-time{
							width: 200upx;
							height: 40upx;
							line-height: 40upx;
							font-size: 24upx;
							padding: 10upx 20upx;
							border-radius: 30upx;
							background-color: #eaf1fb;
							color: #698cde;
							text-align: center;
							position: relative;
							.custom-picker-style{
								position: absolute;
								top: 0;
								right: 0;
								bottom: 0;
								left: 0;			
								line-height: 60upx;
							}
						}
						.remove{
							width: 70upx;
							height: 40upx;
							background-color: #fbf0ee;
							color: #ed6c6d;
							margin-left: 5upx;
						}
					}
				}
			}
		}
		
		
		.add-white-app-post-bottom{
			position: fixed;
			left: 0;
			right: 0;
			bottom: 80upx;
			margin: auto;
			display: flex;
			justify-content: center;
			align-items: center;
			background-color: #eff6fb;
			width: 40%;
			border-radius: 40upx;
			padding: 20upx;
			font-size: 30upx;
			color: #2BC888;
			.txt{
				margin-left: 20upx;
			}
		}
	}
</style>